package com.nulldev.util.net.proxy;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

import com.nulldev.util.string.StringsUtil;
import com.nulldev.util.threading.v3.RunnableWorker;
import com.nulldev.util.threading.v3.ThreadDispatcher;

public class ProxyServer {
	private final int port;
    private final ExecutorService pool;
    private ServerSocket serverSocket;
    private long taskCount;

    public ProxyServer(final int port) {
        this.port = port;
        this.pool = ThreadDispatcher.instance().getExec();
    }
    
    public void start() throws IOException {
    	this.serverSocket = new ServerSocket(port);
    	ThreadDispatcher.instance().addTask(RunnableWorker.fromRunnable(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						final Socket socket = serverSocket.accept();
						ThreadDispatcher.instance().addTask(RunnableWorker.fromRunnable(
								new ProxyServerTask(StringsUtil.randomString(6), socket)));
					}catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
    		
    	}));
    }
    
    public static void main(String[] args) throws IOException {
    	final ProxyServer ps = new ProxyServer(41948);
    	ps.start();
    }
}
